<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        left-icon="phone-o"
        v-model="mobile"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号码"
        :rules="[{ pattern: /^1[3456789]\d{9}$/, message: '请输入手机号码' }]"
      />
      <van-field
        left-icon="points"
        v-model="code"
        name="验证码"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[{ pattern: /^\d{6}$/, message: '请输入6位的验证码' }]"
      >
        <!-- 自定义插槽 -->
        <template #button>
          <van-count-down v-if="counting" @finish="counting=false" :time="60000" format="ss秒" />
          <van-button v-else @click="onSendCode" size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
// 获取接口
import { sendCode, login } from "../utils/api";

export default {
  data() {
    return {
      mobile: "",
      code: "",
      counting: false // 是否显示倒计时
    };
  },
  methods: {
    // 提交表单
    async onSubmit() {
      try {
        let res = await login(this.mobile, this.code);
        // console.log(res)
        // 保存令牌到 vuex 中
        this.$store.commit("setUser", res.data.data);
        // 跳转到首页
        // this.$router.push("/");
        // 返回上一次页面
        this.$router.back()
      } catch (error) {
        // console.log(error)
        this.$toast.fail("登录失败，请重试！");
      }
    },
    // 发送验证码
    async onSendCode() {
      try {
        await sendCode(this.mobile);
        // 显示倒计时
        this.counting = true;
      } catch (error) {
        // 处理错误情况
        if (error.response.status == 429) {
          this.$toast.fail("访问太频繁，稍后再试");
        } else {
          this.$toast.fail("失败，请重试");
        }
      }
    }
  }
};
</script>

<style scoped>
.van-count-down {
  color: #ccc;
}
</style>